package com.hphs.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.hphs.info.ImgInfo;
import com.hphs.info.UploadInfo;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/upload")
public class UploadController {

    private static String filepath="D:/software/nginx-1.21.4/html/";
    private static List<String> imgExits= CollUtil.newArrayList("jpg","png","jpeg","gif");

    @PostMapping
    public String upload(@RequestBody UploadInfo uploadInfo){
        String name=uploadInfo.getName();
        String base64=uploadInfo.getBase64();
        String[] base64s= StrUtil.splitToArray(base64,"base64,");
        byte[] bytes= Base64.decode(base64s[1]);
        name= IdUtil.getSnowflakeNextIdStr()+"-"+name;
        String exit=FileUtil.getSuffix(name);
        String tempFolder="images/";
        if(!imgExits.contains(exit)){
            tempFolder=exit+"/";
        }
        //写入nginx中
        FileUtil.writeBytes(bytes,filepath+tempFolder+name);
        return "http://img.206.com/"+tempFolder+name;
    }
    @GetMapping
    public List<ImgInfo> getImg(){

        List<String> fileNames = FileUtil.listFileNames("D:/software/nginx-1.21.4/html/images/");
        List<ImgInfo> collect = fileNames.stream().map(
                item -> {
                    return new ImgInfo(item, "http://img.206.com/images/"+item);
                }
        ).collect(Collectors.toList());
        return  collect;
    }
}
